package com.wenjie.controller.sys;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.google.code.kaptcha.Producer;
import com.mybatisflex.core.query.QueryWrapper;
import com.wenjie.common.utils.TokenUtil;
import com.wenjie.common.utils.check.CheckUtil;
import com.wenjie.gateway.enums.ClentType;
import com.wenjie.gateway.exception.LoginException;
import com.wenjie.original.entity.SysAdmin;
import com.wenjie.original.entity.table.SysAdminTableDef;
import com.wenjie.original.service.ISysAdminService;
import com.wenjie.original.service.ISysLogLoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api("登录处理")
@RestController
@RequestMapping("/api")
public class LoginController {

    @Value("${password.salt}")
    private String salt;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ISysAdminService sysUserService;

    @Autowired
    private ISysLogLoginService sysLogLoginService;

    /**
     * BufferedImage 编码转换为 base64
     *
     * @param bufferedImage
     * @return
     */
    private static String bufferedImageToBase64(BufferedImage bufferedImage) {
        ByteArrayOutputStream bao = new ByteArrayOutputStream();//io流
        try {
            ImageIO.write(bufferedImage, "jpg", bao);//写入流中
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = Base64.getEncoder().encode(bao.toByteArray());
        String base64 = new String(bytes);
        base64 = base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
        return "data:image/png;base64," + base64;
    }

    @ApiOperation("登录")
    @PostMapping("/login")
    public HashMap<String, Object> login( @RequestBody @Validated Admin admin) {

        if (CheckUtil.checkPhone(admin.getTel())) {
            // 查验一下验证码
//            Object code = redisTemplate.opsForValue().get("captcha_codes:" + admin.getUuid());
//            if (code == null || !String.valueOf(code).equals(admin.getCode())) throw new LoginException("验证码不正确");

            // 对密码后端也进行一次加盐
            admin.setPassword(DigestUtil.md5Hex(admin.getPassword() + salt));

            SysAdmin sysAdmin = sysUserService.getOne(new QueryWrapper().where(SysAdminTableDef.SYS_ADMIN.TEL.eq(admin.getTel())).and(SysAdminTableDef.SYS_ADMIN.PASSWORD.eq(admin.getPassword())));
            if (sysAdmin == null) {
                sysLogLoginService.failInfo();
                throw new LoginException("账号或密码不正确");
            }
            sysAdmin.setPassword("");
            HashMap<String, Object> restMap = new HashMap<>();
            restMap.put("userInfo", sysAdmin);
            restMap.put("token", TokenUtil.createToken(sysAdmin.getSysAdminId(), ClentType.BACK_END));


            // 添加一下登录记录
            sysLogLoginService.sucInfo(sysAdmin);

            return restMap;
        } else throw new LoginException("手机号格式不正确");
    }


    @ApiOperation("生成验证码")
    @PostMapping("/captchaImage")
    public Map<String, String> getCode(HttpServletResponse response) {
        Map<String, String> restMap = new HashMap<>();
        // 保存验证码信息
        String uuid = IdUtil.getSnowflakeNextIdStr();
        String verifyKey = "captcha_codes:" + uuid;

        String capStr, code;
        BufferedImage image;

        String capText = captchaProducerMath.createText();
        capStr = capText.substring(0, capText.lastIndexOf("@"));
        code = capText.substring(capText.lastIndexOf("@") + 1);
        image = captchaProducerMath.createImage(capStr);
        redisTemplate.opsForValue().set(verifyKey, code, 2, TimeUnit.MINUTES);

        restMap.put("uuid", uuid);
        restMap.put("img", bufferedImageToBase64(image));
        return restMap;
    }

    @Data
    public static class Admin {
        //        @NotBlank
//        private String code;
//        @NotBlank
//        private String uuid;
        @NotBlank
        private String tel;
        @NotBlank
        private String password;
    }

}
